package aop.test1;


import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;

import java.lang.reflect.Method;

class MyMethodInterceptor implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        System.out.println("方法执行之前：" + methodInvocation.getMethod().toString());
        Object result = methodInvocation.proceed();
        System.out.println("方法执行之后：" + methodInvocation.getMethod().toString());
        return result;
    }
}

class MyMethodBeforeAdvice implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("前置增强");
    }
}


class MyAfterReturningAdvice implements AfterReturningAdvice {
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("后置增强");
    }
}


class User {

    public void helloWorld() {
        System.out.println("你好！");
    }

    public void error() {
        throw new RuntimeException("Error");
    }
}


public class Main {

    public static void main(String[] args) {


        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTarget(new User());
        proxyFactory.addAdvice(new MyThrowsAdvice());
        proxyFactory.addAdvice(new MyMethodInterceptor());
        proxyFactory.addAdvice(new MyMethodBeforeAdvice());
        proxyFactory.addAdvice(new MyAfterReturningAdvice());
        User proxyUser = (User) proxyFactory.getProxy();
        proxyUser.helloWorld();

        proxyUser.error();

    }
}
